﻿#define _CRT_SECURE_NO_WARNINGS 1
#include"SList.h"

//初始化
void SLInit(SL* ps)
{
	ps->a = (SLDataType*)malloc(sizeof(SLDataType) * 4);
	ps->capacity = 4;  //给一定的初始空间
	ps->size = 0;
}


//销毁
void SLDestroy(SL* ps)
{
	ps->a = nullptr;
	ps->capacity = ps->size = 0;
}

//打印顺序表元素
void SLPrint(SL* ps)
{
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}


//扩容
void SLCheckCapacity(SL* ps)
{
	if (ps->capacity == ps->size)
	{
		int newCapacity = ps->capacity * 2;
		SLDataType* tmp = (SLDataType*)realloc(ps->a,newCapacity * sizeof(SLDataType));
		if (tmp == nullptr)
		{
			perror("realloc fail!");
			exit(1);
		}
		ps->a = tmp;
		ps->capacity = newCapacity;
	}
}


//尾插
void SLPushBack(SL* ps, SLDataType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	ps->a[ps->size++] = x;
}


//尾删
void SLPopBack(SL* ps)
{
	assert(ps and ps->size);
	ps->size--;
}

//头插
void SLPushFront(SL* ps, SLDataType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	//整体向后移动一位
	for (int i = ps->size ; i > 0; i--)
	{
		ps->a[i] = ps->a[i - 1];
	}
	ps->a[0] = x;
	ps->size++;
}


//头删
void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size);
	//整体向前移动一位
	for (int i = 0; i < ps->size - 1; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}
	ps->size--;
}

//指定位置之前插⼊数据
void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	//将指定位置之后的数据都向后移动一位
	for (int i = ps->size-1; i >=pos-1; i--)
	{
		ps->a[i+1] = ps->a[i];
	}
	ps->a[pos-1] = x;
	ps->size++;
}


//指定位置之后删除数据
void SLErase(SL* ps, int pos)
{
	assert(ps);
	for (int i = pos; i < ps->size; i++)
	{
		ps->a[i-1] = ps->a[i];
	}
	ps->size--;
}


int SLFind(SL* ps, SLDataType x)
{
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x) {
			return i;
		}
	}
	return -1;
}